<?php

namespace App\Admin\Controllers;

use App\Models\Orderdetail;
use App\Models\InventoryFunc;

//use Encore\Admin\Form;
use Encore\Admin\Grid;
use Encore\Admin\Facades\Admin;
use Encore\Admin\Layout\Content;
use App\Http\Controllers\Controller;
use Encore\Admin\Controllers\ModelForm;
use Illuminate\Http\Request;
use Encore\Admin\Widgets\Table;
use Encore\Admin\Widgets\Form as myForm;


class OutsController extends Controller
{
    use ModelForm;

    /**
     * Index interface.
     *
     * @return Content
     */
    public function index()
    {
        return Admin::content(function (Content $content) {

            $content->header('出库管理');
            $content->description('Outs');

            $content->body($this->grid());
        });
    }

    /**
     * Make a grid builder.
     *
     * @return Grid
     */
    protected function grid()
    {
        return Admin::grid(Orderdetail::class, function (Grid $grid) {
            $grid->model()->select('order_detail.*','order_detail.id as detail_id','company.name','agent.name as agent_name',
                'sku.name as sku_name',
                //'warehouse.name as warehouse_name'
                'order.*','admin_users.name as operater_name')
            ->leftjoin('order','order.id','=','order_detail.order_id')
            ->leftjoin('company','company.id','=','order.company_id')
            ->leftjoin('agent','agent.id','=','order.agent_id')
            ->leftjoin('admin_users','admin_users.username','=','order.operater_id')
            ->leftjoin('sku','sku.id','=','order_detail.sku_id')
            ->where('order.company_id',Admin::user()->company_id)
            ->orderBy('order.created_at', 'desc');
            //->leftjoin('warehouse','warehouse.warehouse_id','=','order.warehouse_id');
            $grid->order_id('销售单编号')->sortable();
            $grid->agent_name('客户名称');
            $grid->sku_name('SKU名称');

            $grid->name('所属公司');
            $grid->operater_name('销售员');
            $grid->out_state('出库状态')->display(function($v){
                return HelpersController::getStateValue('outState',$v);
            });
            // $grid->total_amount('含税金额')->display(function($v){return round($v,2);});
            // $grid->exchange_amount('汇率后含税价')->display(function($v){return round($v,2);});
            // $grid->tax('税额')->display(function($v){return round($v,2);});
            // $grid->exchange_rate('汇率')->display(function($v){return $v."%";});
            // $grid->rate('税率')->display(function($v){return $v."%";});
            //$grid->created_at('创建时间');
            //$grid->updated_at('更新时间');
            //$grid->arrive_time('到货时间');
            //$grid->bar_code('条形码url');
            //$grid->warehouse_name('仓库编号');
            // $grid->pay_type('付款方式');
            // $grid->pay_status('付款状态');
            // $grid->paid_amount('已付金额');
            //$grid->purchase_type('采购单类型');
            //$grid->remark('备注');
            $grid->review_state("审核状态")->display(function($v){
                return HelpersController::getStateValue('orderReviewState',$v);
            });
            $grid->disableCreateButton();//禁用新增按钮
            $grid->disableExport();//禁用导出按钮
            $grid->actions(function ($actions) {
                // append一个操作
                $actions->disableEdit();
                $actions->disableDelete();//禁用删除
                $actions->prepend('<a href="'.\Route('outs.show',['id'=>$actions->row['detail_id']]).'"><i class="fa fa-eye"></i></a>');
            });

             $grid->filter(function($filter){
                // 去掉默认的id过滤器
                $filter->disableIdFilter();

                $filter->where(function ($query) {
                    $query->where('order_detail.order_id', 'like', "%{$this->input}%");
                }, '销售单编号');

                $filter->where(function ($query) {
                    $query->where('agent.name', 'like', "%{$this->input}%");
                }, '客户名称');

                $filter->where(function ($query) {
                    $query->where('sku.name', 'like', "%{$this->input}%");
                }, 'SKU名称');

                $filter->where(function ($query) {
                    $query->where('admin_users.name', 'like', "%{$this->input}%");
                }, '销售员');

                // $filter->where(function ($query) {

                //     $query->where('order.operater_id',$this->input);

                // }, '销售员')->select(\DB::table('admin_users')->leftjoin('admin_role_users','admin_role_users.user_id','=','admin_users.id')->where('admin_role_users.role_id','4')->pluck(\DB::raw('admin_users.name'),\DB::raw('admin_users.username')));
            });
        });
    }

    public function show($id)
    {
        $data = \DB::table('order_detail')->select('admin_users.name as user_name','company.name as company_name','agent.name as agent_name'
            //,'warehouse.name as warehouse_name'
            ,'order.*','order_detail.*','sku.name as sku_name','batch_grade.name as batch_grade','batch_thick.name as batch_thick','batch_origin.name as batch_origin','batch_colour.name as batch_colour','batch_avg_size.name as batch_avg_size','batch_min_size.name as batch_min_size','reviewer.name as reviewer_name')
                        ->leftjoin('order','order.id','=','order_detail.order_id')
                        ->leftjoin('admin_users','admin_users.username','=','order.operater_id')
                        // ->leftjoin('admin_users as documentary','documentary.username','=','agent.merchandiser')
                        // ->leftjoin('admin_users as salesman','salesman.username','=','agent.salesman')
                        ->leftjoin('admin_users as reviewer','reviewer.username','=','order.reviewer_id')
                        ->leftjoin('company','company.id','=','order.company_id')
                        ->leftjoin('agent','agent.id','=','order.agent_id')
                        //->leftjoin('warehouse','warehouse.warehouse_id','=','purchase.warehouse_id')
                        ->leftjoin('sku','order_detail.sku_id','=','sku.id')
                        ->leftjoin('batchattribute as batch_grade','order_detail.grade','=','batch_grade.id')
                        ->leftjoin('batchattribute as batch_thick','order_detail.thick','=','batch_thick.id')
                        ->leftjoin('batchattribute as batch_origin','order_detail.origin','=','batch_origin.id')
                        ->leftjoin('batchattribute as  batch_colour','order_detail.colour','=','batch_colour.id')
                        ->leftjoin('batchattribute as batch_avg_size','order_detail.avg_size','=','batch_avg_size.id')
                        ->leftjoin('batchattribute as batch_min_size','order_detail.min_size','=','batch_min_size.id')
                        ->where('order_detail.id',$id)->first();

 $content = '<div style="width:80%;margin:0 auto;background:#fff;padding:10px;"><h4 style="text-align:center;">基本信息</h4><hr>';
        $headers = [];
        $rows = [
            ['销售单编号', $data->order_id,'订单类型', HelpersController::getStateValue('orderType',$data->type)],
            ['客户编号', $data->agent_name,'物流方式', HelpersController::getStateValue('Logistics',$data->logistics)],
            ['所属公司', $data->company_name,'有货先发？', $data->is_send?"是":"否"],
            ['出库时间',$data->send_time,($data->type==0?"":"外协入库时间"),($data->type==0?"":$data->arrive_time)]
        ];
        $table_1 = new Table($headers, $rows);
        $content .= $table_1->render();
        $content .= '<h4 style="text-align:center;">系统信息</h4><hr>';

        // table 2
        $headers = [];

        $rows = [
            ['操作人',$data->user_name,'销售单状态', HelpersController::getStateValue('orderState',$data->out_state)],
            ['销售',isset($data->salesman)?$data->salesman:'未维护该客户销售','跟单', isset($data->documentary_name)?$data->documentary_name:'未维护该客户跟单' ],
            ['最后操作人',$data->reviewer_name,'最后操作时间',$data->review_time],
            ['单据生成时间', $data->created_at,'',''],
        ];

        $table_2 = new Table($headers, $rows);
        $content .=  $table_2->render();

        $content .= '<h4 style="text-align:center;">SKU信息</h4><hr>';

        // table 2
        $headers = [];

        $rows = [
            ['SKU编号',$data->sku_id,'SKU名称', $data->sku_name ],
            ['合同订单编号',$data->contract_id,'原始单号',$data->original_id ],
            ['皮源编号', $data->cowhide_id,'出库状态', HelpersController::getStateValue('outState',$data->out_state),'',''],
            ['等级',$data->batch_grade?$data->batch_grade:"未维护",'厚度',$data->batch_thick?$data->batch_thick:"未维护" ],
            ['产地', $data->batch_origin?$data->batch_origin:"未维护",'颜色',$data->batch_colour?$data->batch_colour:"未维护"],
            ['平均尺寸', $data->batch_avg_size?$data->batch_avg_size:"未维护",'最小尺寸',$data->batch_min_size?$data->batch_min_size:"未维护"],
        ];
        $table_3 = new Table($headers, $rows);

        $content .=  $table_3->render();

        $content .= "<h4 style='text-align:center'>备注</h4><hr><p style='background:#efefef;padding:8px;'>".(trim($data->remark)?$data->remark:"无")."</p>";
/* 仓库不允许查看财务状态

        $content .= '<h4 style="text-align:center;">财务状态</h4><hr>';

        //     $table->tinyInteger('invoice')->nullable()->comment('是否开发票');
        //     $table->decimal('invoice_money',11,4)->nullable()->comment('发票费用');

        //     $table->string('remark')->nullable()->comment('备注');
        // table 1

        // if($data->reviewer_id){
            $headers = [];
            $rows = [
                ['支付方式', $data->pay_type==0?"现金":($data->pay_type==1?"电汇":($data->pay_type==2?"支票":($data->pay_type==3?"其它":"未知"))), '支付状态', $data->payment_state==0?"未付款":($data->payment_state==1?"部分付款":($data->payment_state==2?"全款":"未知"))],
                ['订单总价',round($data->total_price,2)."元","优惠金额",round($data->total_price - $data->actual_money)."元"],
                ["实付金额", round($data->actual_money,2)."元","已付款金额",round($data->pay_money,2)."元" ],
                ['财务审核', isset($data->reviewer_name)?$data->reviewer_name:"未审核", "审核时间",isset($data->review_time)?$data->review_time:"未审核"],
            ];
            $table = new Table($headers, $rows);
            $content .=  $table->render();
*/
        $content .= '<h4 style="text-align:center;">仓库设置</h4><hr>';
        $form = new myForm();
        $form->__construct(
            [
                'sku_id'=>$data->sku_id,
                'sku_name'=>$data->sku_name,
                'out_state'=>$data->out_state,
            ]);
        $form->action($data->id.'/finance');
        $form->method('POST');
        $form->disablePjax();
        $form->hidden('order_detail_id')->default($data->id);
        $form->hidden('order_id')->default($data->order_id);
        $form->hidden('sku_id')->default($data->sku_id);
        $form->display('sku_name','sku');
        $outStateOption = HelpersController::getStateOptions('outState');
        array_shift($outStateOption);
        $form->radio('out_state','出库状态')->options($outStateOption);
        $hadOut = \DB::table('inventory_checking_detail')
            ->select(\DB::raw('sum(num) as num'),\DB::raw('sum(size) as size'))
            ->where([
                'checking_ASN'=>$data->order_id,
                'type'=>1,
                'sku_id'=>$data->sku_id,
                'grade_o'=>$data->grade,
                'thick_o'=>$data->thick,
                'origin_o'=>$data->origin,
                'colour_o'=>$data->colour,
                'avg_size_o'=>$data->avg_size,
                'min_size_o'=>$data->min_size
            ])
            ->first();
        $form->currency('arrive_num','实际出库张数')->symbol("")->help('单据数量： '.round($data->num,2).' ，已出库张数: '.round($hadOut->num,2));
        $form->currency('arrive_size','实际出库尺数')->symbol("")->help('单据数量： '.round($data->size,2).' ，已出库尺数: '.round($hadOut->size,2));
        // $form->html('<button type="button" class="btn">选择批次</button>','');
        $form->select('inventory_sn','批次')->options(
            \DB::table('inventory')
                ->leftjoin('warehouse','warehouse.id','=','inventory.warehouse_id')
                ->where([['sku_id','=',$data->sku_id],['over_size','>',0],['warehouse.company_id','=',Admin::user()->company_id]])
                ->pluck('inventory.inventory_id','inventory.id')
        );
        $form->html("<div id='batch_info'></div>");

        if($data->review_state == "FINANCE_1ST"){
            if($data->out_state == "ALL_OUT"){
                $content.='<p style="text-align:center"> 已全部出库</p>';
            }else{
                $content .= $form->render();
            }

        }elseif($data->review_state == "OUT_CHECK"){
            $content.='<p style="text-align:center"> 单据已完成出库</p>';
        }else{
            $content.='<p style="text-align:center"> 需要等待财务审核通过后操作</p>';
        }

        $content.='
            <script>
                $(document).off("change",".inventory_sn");
                $(document).on("change",".inventory_sn", function(e){
                    var bid = $(this).val();
                    if(!bid){
                        return;
                    }
                    $.ajax({
                      method: "POST",
                      url: "/admin/outs/batchInfo",
                      data: { bid: bid}
                    }).success(function( msg ) {
                        msg = JSON.parse(msg);
                        if(msg){
                            var html = "";
                            html +="<table class=\'table\'>";
                            html +="<tr><td>入库时间</td><td>"+msg.created_at+"</td><td>可用尺数</td><td>"+msg.over_size+"</td><td>可用张数</td><td>"+msg.over_num+"</td>"
                            html +="<tr><td>厚度</td><td>"+(msg.batch_thick?msg.batch_thick:"-")+"</td><td>等级</td><td>"+(msg.batch_grade?msg.batch_grade:"-")+"</td><td>产地</td><td>"+(msg.batch_origin?msg.batch_origin:"-")+"</td>"
                            html +="<tr><td>颜色</td><td>"+(msg.batch_colour?msg.batch_colour:"-")+"</td><td>平均尺寸</td><td>"+(msg.batch_avg_size?msg.batch_avg_size:"-")+"</td><td>最小尺寸</td><td>"+(msg.batch_min_size?msg.batch_min_size:"-")+"</td>"
                            html +="<tr><td>所在仓库</td><td>"+msg.warehouse_name+"</td><td>仓库库区</td><td>"+msg.warehouse_zone_name+"</td><td>仓库库位</td><td>"+msg.warehouse_location_name+"</td>"

                            html +="</table>";
                            $("#batch_info").html(html);
                        }else{
                            $("#batch_info").html("批次拉取出错")
                        }
                    });
                });
            </script>
        ';


        // $content .= '<h4 style="text-align:center;">仓库设置</h4><hr>';
        // $form = new myForm();
        // $form->action('example');
        // $form->select('logistics','物流方式')->options(['物流','自提','其它']);
        // $form->select('order_status','发货状态')->options([2=>'部分发货',3=>'已发货']);
        // foreach($detail_data as $v){
        //     $row = [$v->sku_name, $v->num,$v->arrive_num,$v->price,$v->batch_grade,$v->batch_thick,$v->batch_origin,$v->batch_colour,$v->batch_avg_size,$v->batch_min_size];
        //     array_push($rows, $row);
        // }
        // $content .= $form->render();

        $items = [
            'header'      => '出库处理',
            'description' => 'Outs',
            'breadcrumb'  => '',
            'content'     => $content."</div>",
        ];

        return view('admin::content', $items)->render();
    }

    /**
     * @param $id
     * @return \Illuminate\Http\RedirectResponse|\Illuminate\Routing\Redirector
     * @throws \Exception
     */
    public function finance($id){
        $input = \Illuminate\Support\Facades\Input::all();
        $old = \DB::table('order')->where('id',$input['order_id'])->first();
        // if($old->order_state == 3 ){
        //     admin_toastr("订单已全部出库,如要变更请联系系统管理员");
        //     return back()->withInput();
        // }
        if($old->order_state == "ALL_OUT" ){
            admin_toastr("该SKU已全部出库,如要变更请联系系统管理员",'error');
            return back()->withInput();
        }
        if(!isset($input['out_state'])){
            admin_toastr("出库状态必填","error");
            return back()->withInput();
        }
        if($input['arrive_num']<=0){
            admin_toastr("出库张数至少大于0","error");
            return back()->withInput();
        }

        if($input['arrive_size']<=0){
            admin_toastr("出库尺寸至少大于0","error");
            return back()->withInput();
        }
        if(!$input['inventory_sn']){
            admin_toastr("出库批次必须选择","error");
            return back()->withInput();
        }
        // $hadOut = \DB::table('inventory_checking_detail')->select(\DB::raw('sum(num) as num'),\DB::raw('sum(size) as size'))->where(['checking_ASN'=>$input['order_id'],'type'=>1,'sku_id'=>$input['sku_id']])->first();
        $inventory = \DB::table('inventory')->where(['id'=>$input['inventory_sn'],'sku_id'=>$input['sku_id']])->first();

        $inventoryNumCnt = $inventory->over_num;
        $inventorySizeCnt = $inventory->over_size;
        if($input['arrive_num'] > $inventoryNumCnt){
            admin_toastr("该批次没有那么多数量张数的库存","error");
            return back()->withInput();
        }
        if($input['arrive_size'] > $inventorySizeCnt){
            admin_toastr("该批次没有那么多数量尺寸的库存","error");
            return back()->withInput();
        }

        // $olddetail = \DB::table('order_detail')->where('id',$id)->first();
        // $validator = \Validator::make($input, [
        //     'order_state' => 'required',
        //     'arrive_num'=>'required',
        //     // 'warehouse_id'=>'required',
        //     // 'warehouse_zone_id'=>'required',
        //     // 'warehouse_location_id '=>'required',
        //     'inventory_id' => 'required'
        // ]);
        // if ($validator->fails()) {
        //     return back()->withInput()->withErrors($validator->errors());
        // }
        $old_details = \DB::table('order_detail')->where([['id','<>',$id],['order_id',$input['order_id']]])->get();
        if(count($old_details) > 0){
            if($input['out_state'] == "PART_OUT"){
                $operate_state = "PART_OUT";
            }else{
                $operate_state = "ALL_OUT";
                foreach ($old_details as $old_detail) {
                    if($old_detail->out_state != "ALL_OUT"){
                        $operate_state = "PART_OUT";
                        break;
                    }
                }
            }
        }else{
            $operate_state = $input['out_state'];
        }
        $update_order_datas['order_state'] = $operate_state;
        if($operate_state == "ALL_OUT"){
            $update_order_datas['review_state'] = "OUT_CHECK";
        }
        $model = new InventoryFunc("order",$id);
        try{
            \DB::beginTransaction();
            $model->insertInventoryAndCheckingOne($input);
            \DB::table('order')->where(['id'=>$input['order_id']])->update($update_order_datas);
            \DB::table('order_detail')->where(['id'=>$id])->update(['out_state'=>$input['out_state']]);
            \DB::commit();

            admin_toastr("出库成功");
            $url = route('outs.index');
            return redirect($url);
        }catch (Exception $e) {
            \DB::rollBack();
            admin_toastr("数据库出错，请联系管理员","error");
            return back()->withInput();

        }
    }


    function batchInfo(Request $req){
        $arr = $req->all();
        $bid = $arr['bid'];
        return json_encode(\DB::table('inventory')->select(
                'sku.name as sku_name',
                'warehouse.name as warehouse_name',
                'warehouse_zone.name as warehouse_zone_name',
                'warehouse_location.name as warehouse_location_name',
                'inventory.*',
                'batch_grade.name as batch_grade',
                'batch_thick.name as batch_thick',
                'batch_origin.name as batch_origin',
                'batch_colour.name as batch_colour',
                'batch_avg_size.name as batch_avg_size',
                'batch_min_size.name as batch_min_size'
            )
            ->leftjoin('sku','sku.id','=','inventory.sku_id')
            ->leftjoin('warehouse','warehouse.id','=','inventory.warehouse_id')
            ->leftjoin('warehouse_zone','warehouse_zone.id','=','inventory.warehouse_zone_id')
            ->leftjoin('warehouse_location','warehouse_location.id','=','inventory.warehouse_location_id')
            ->leftjoin('batchattribute as batch_grade','inventory.grade','=','batch_grade.id')
            ->leftjoin('batchattribute as batch_thick','inventory.thick','=','batch_thick.id')
            ->leftjoin('batchattribute as batch_origin','inventory.origin','=','batch_origin.id')
            ->leftjoin('batchattribute as  batch_colour','inventory.colour','=','batch_colour.id')
            ->leftjoin('batchattribute as batch_avg_size','inventory.avg_size','=','batch_avg_size.id')
            ->leftjoin('batchattribute as batch_min_size','inventory.min_size','=','batch_min_size.id')
            ->where('inventory.id',$bid)->first());
    }
}
